<?php
namespace  crontab\event;
use crontab\lib\Actuator;
//加载配置
require_once dirname(__DIR__).'/db_config.php';

class ExecEvent {
	//数据库连接句柄
    public  static $dbCon= null;

	//主进程初始化子进程的回调函数
    public static function onWorkerStart($worker){
        //如果想mysql提高查询效率,可以维护一个mysql链接池 需要共享变量的服务,
        if($worker->id == 0){
            echo "\033[32;40m---------------------------执行器启动成功--------------------------------\033[0m".PHP_EOL;
        }
    }

    public static function onMessage($connection, $taskid) {

        //收到数据 进行连接销毁
        $connection->destroy();
        //to do task logic
        global $db_config;
        static::$dbCon = new \Workerman\MySQL\Connection(
            $db_config['host'], 
            $db_config['port'], 
            $db_config['user'], 
            $db_config['password'], 
            $db_config['database']
        );
        $info = self::getTaskOne($taskid);
        if($info){
            //匹配任务执行器
            $class = $info['type'];
            $resObj   =  Actuator::$class()->doRun($info);
            $res = $resObj->getData();
            $res['tid'] = $taskid;
            $res['create_time'] = time();
            $insert_id = static::$dbCon->insert('we_task_log')->cols([
                'tid'=>$taskid,
                'create_time'    =>time(),
                'status_code'    =>$res['result_status'],
                'result_content' =>$res['result_content'],
            ])->query();
            if(!$insert_id){
                echo $taskid."\033[0;31m--------任务id==={$taskid}====写入日志失败--------\033[0m".PHP_EOL;
            }
        }
        //销毁连接
        static::$dbCon = null;
    }



    public static function onClose($connection){

    }

    public static function onError($connection){
    	
    }

    //获取一条数据
    public static  function  getTaskOne($id){

        $info = static::$dbCon->select('*')
                              ->from('we_task')
                              ->where('id= :id')
                              ->bindValues(['id'=>$id])
                              ->row();
        return  $info;
    }

}
